package com.uwo.commons.ibatis.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

/**
 * mybatis 配置
 * @author hao.yan
 */
@Order(2)
@Configuration
public class MybatisConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MybatisConfiguration.class);

    @Autowired
    private DataSource dataSource;

    @Autowired
    private MybatisProperties mybatisProperties;

    /**
     * 事务
     * @return
     */
    @Bean(name = "transactionManager")
    @ConditionalOnMissingBean
    public DataSourceTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * sessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "sessionFactory")
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        log.debug("create session factory");
        if(dataSource == null)
            return null;
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        if(null != mybatisProperties && !StringUtils.isEmpty(mybatisProperties.getTypePackage())) {
            log.debug("typePackage = {}", mybatisProperties.getTypePackage());
            sessionFactory.setTypeAliasesPackage(mybatisProperties.getTypePackage());
        }
        log.debug("mapper package = {}", mybatisProperties.getMapperPackages());
        log.debug("mapperLocations = {}", mybatisProperties.getMapperLocations());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(mybatisProperties.getMapperLocations()));
        log.debug("create session factory");
        return sessionFactory.getObject();
    }

}
